<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>flatten</title>
</head>

<body>
    <div>打开浏览器控制台查看结果</div>
    <script>
        const flatten = (arr, depth = 1) =>
            arr.reduce(
                (a, v) =>
                    a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v),
                []
            );
        console.log(flatten([1, [2], 3, 4])); // [1, 2, 3, 4]
        console.log(flatten([1, [2, [3, [4, 5], 6], 7], 8], 2)); // [1, 2, 3, [4, 5], 6, 7, 8]
    </script>
</body>

</html>